﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using ChiakiYu.Common.Data;
using ChiakiYu.Common.Extensions;
using ChiakiYu.Core.AutoMapper;
using ChiakiYu.Model.Roles;
using ChiakiYu.Model.Users;
using ChiakiYu.Service.Authorization;
using ChiakiYu.Service.Roles;
using ChiakiYu.Service.Roles.Dto;
using ChiakiYu.Service.Users;
using ChiakiYu.Service.Users.Dto;
using ChiakiYu.Web.Areas.Admin.ViewModels;
using ChiakiYu.Web.Controllers;

namespace ChiakiYu.Web.Areas.Admin.Controllers
{
    //[ManageAuthorize(RequireSystemAdministrator = true)]

    [EnablePermission("用户")]
    public partial class AdminUserController : BaseController
    {
        #region 构造函数

        public AdminUserController(IUserService userService,
            IRoleService roleService, IAuthorizationService authorizationService)
        {
            _userService = userService;
            _roleService = roleService;
            _authorizationService = authorizationService;
        }

        #endregion

        #region 私有字段

        private readonly IUserService _userService;
        private readonly IRoleService _roleService;
        private readonly IAuthorizationService _authorizationService;

        #endregion

        #region 用户

        /// <summary>
        ///     用户管理
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页数据数</param>
        /// <returns></returns>
        [EnablePermission("用户管理")]
        public virtual ActionResult ManageUsers(int pageIndex = 1, int pageSize = 2)
        {
            #region 组装搜索条件

            var input = new GetUsersInput
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                KeyWords = Request.QueryString.Get("KeyWords", string.Empty)
                //IsActive = Request.QueryString.Get<bool?>("IsActive", null)
            };

            #endregion

            #region 组装搜索下拉列表

            //var activatedValues = new Dictionary<bool, string> {{true, "已激活"}, {false, "未激活"}};
            //ViewData["IsActived"] =new SelectList(activatedValues.Select(n => new {text = n.Value, value = n.Key.ToString().ToLower()}),"value", "text", input.IsActive);

            #endregion

            var user = _userService.GetUsers(input);

            return View(user);
        }


        /// <summary>
        ///     添加用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [EnablePermission("添加用户")]
        public virtual ActionResult AddUser()
        {
            var model = new UserEditModel();
            return View("EidtUser", model);
        }

        /// <summary>
        ///     编辑用户
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpGet]
        [EnablePermission("编辑用户")]
        public virtual ActionResult EidtUser(long userId)
        {
            var model = new UserEditModel();
            var user = _userService.GetUser(userId);
            model = user.MapTo<UserEditModel>();
            return View(model);
        }

        /// <summary>
        ///     编辑用户提交
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public virtual ActionResult EidtUser(UserEditModel model)
        {
            if (!ModelState.IsValid)
                return Json(new MessageData(MessageType.Hint, "请将信息填写完整"));

            string message = string.Empty;
            if (model.Id > 0) //修改
            {
                message = "修改成功";
            }
            else//新增
            {
                var user = new User
                {
                    UserName = model.UserName,
                    Email = model.Email,
                    EmailConfirmed = true,
                    Mobile = model.Mobile,
                    MobileConfirmed = true,
                    NickName = model.NickName,
                    Password = UserPasswordHelper.MD5("123123")
                };

                var isExit = _userService.CheckUserInfo(user, out message);
                if (!isExit)
                    return Json(new MessageData(MessageType.Hint, message));
                if (_userService.AddUser(user).Id > 0)
                    message = "创建成功，初始密码为：123123";
                else
                    return Json(new MessageData(MessageType.Hint, "创建失败，请重试"));
            }

            return Json(new MessageData(MessageType.Success, message));
        }

        /// <summary>
        ///     删除用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [EnablePermission("删除用户")]
        public virtual JsonResult DeleteUser()
        {
            return Json(new MessageData(MessageType.Success, "删除成功！"));
        }

        #endregion

        #region 角色

        /// <summary>
        ///     角色管理
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页数据数</param>
        /// <returns></returns>
        [EnablePermission("角色管理")]
        public virtual ActionResult ManageRoles(int pageIndex = 1, int pageSize = 5)
        {
            var input = new GetRolesInput
            {
                PageIndex = pageIndex,
                PageSize = pageSize
            };
            var roles = _roleService.GetRoles(input);

            return View(roles);
        }

        /// <summary>
        ///     编辑角色
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <returns></returns>
        [HttpGet]
        [EnablePermission("编辑角色")]
        public virtual ActionResult EidtRole(int roleId)
        {
            return View();
        }

        /// <summary>
        ///     编辑用户提交
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public virtual JsonResult EidtRole()
        {
            return Json(new MessageData(MessageType.Success, "设置成功！"));
        }


        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [EnablePermission("删除角色")]
        public virtual JsonResult DeleteRole(int roleId)
        {
            return Json(new MessageData(MessageType.Success, "删除成功！"));
        }

        /// <summary>
        ///     设置角色 页面
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [EnablePermission("设置角色")]
        public virtual ActionResult SetRoles(long userId)
        {
            var user = _userService.GetUser(userId);

            var roles = _roleService.GetRoles();
            var list = user.Roles.MapTo<List<RoleDto>>();

            ViewData["UserId"] = userId;
            ViewData["UserRoleList"] = list;
            return View(roles);
        }

        /// <summary>
        ///     设置角色提交表单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public virtual JsonResult SetRoles()
        {
            var userId = Request.Form.Get<long>("userId", 0);
            if (userId <= 0)
            {
                return Json(new MessageData(MessageType.Hint, "请选择某个用户设置角色！"));
            }
            var roleIdStr = Request.Form.Get("roleId");

            if (string.IsNullOrEmpty(roleIdStr))
                return Json(new MessageData(MessageType.Hint, "请至少分配一项角色！"));
            var roleIds = roleIdStr.Split(',');
            var roles = _roleService.GetRolesByIds(roleIds.Select(item => Convert.ToInt32(item)));

            var user = _userService.GetUser(userId);
            user.Roles.Clear();
            user.Roles = roles;
            _userService.UpdateUser(user);

            return Json(new MessageData(MessageType.Success, "设置成功！"));
        }

        #endregion

        #region 权限设置

        /// <summary>
        ///     更改权限 页面
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [EnablePermission("更改权限")]
        public virtual ActionResult ChangePermissions(int roleId)
        {
            var role = _roleService.GetRole(roleId);
            var rolePermissions = role.Permissions.ToList();

            ViewData["RolePermissions"] = rolePermissions;
            ViewData["PermissionsOfAssembly"] = _permissionsOfAssembly;
            ViewData["RoleId"] = roleId;
            return View(rolePermissions);
        }

        /// <summary>
        ///     更改权限 提交表单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public virtual JsonResult ChangePermissions()
        {
            var roleId = Request.Form.Get("roleId", 0);
            if (roleId <= 0)
            {
                return Json(new MessageData(MessageType.Hint, "请选择某个角色更改权限！"));
            }

            var permissionIds = Request.Form.Get("Id"); //获取表单提交过来的权限Id


            if (string.IsNullOrEmpty(permissionIds))
                return Json(new MessageData(MessageType.Hint, "设置失败"));
            var permissionIdArray = permissionIds.Split(',');

            var role = _roleService.GetRole(roleId); //获取设置权限的角色

            //先删除该角色下的所有权限
            if (!_authorizationService.DeleteRolePermissions(roleId))
                return Json(new MessageData(MessageType.Hint, "设置失败,请重试"));
            //给该角色添加新的权限
            foreach (var item in permissionIdArray)
            {
                var permission = _permissionsOfAssembly.FirstOrDefault(n => n.Id == item);
                if (permission != null)
                {
                    var rolePermission = new RolePermission
                    {
                        RoleId = roleId,
                        Controller = permission.Controller,
                        ControllerDescription = permission.ControllerDescription,
                        Action = permission.Action,
                        ActionDescription = permission.ActionDescription,
                        Params = permission.Params
                    };
                    role.Permissions.Add(rolePermission);
                }
            }
            _roleService.UpdateRole(role);
            var userNames = role.Users.Select(n => n.UserName);
            ClearUserPermissionsCache(userNames);
            return Json(new MessageData(MessageType.Success, "设置成功！"));
        }

        /// <summary>
        /// 清楚用户的权限列表缓存
        /// </summary>
        /// <param name="userNames"></param>
        private void ClearUserPermissionsCache(IEnumerable<string> userNames)
        {
            if (userNames != null && userNames.Any())
            {
                foreach (var item in userNames)
                {
                    System.Web.HttpContext.Current.Session.Remove("UserPermissions_" + item);
                }
            }
        }

        #endregion
    }
}